<?php
/**
 * Created by PhpStorm.
 * User: Administratorjing
 * Date: 2018/7/29/029
 * Time: 13:45
 */

namespace App\Services;


use App\Exceptions\InternalException;
use App\Jobs\CloseOrder;
use App\Models\Order;
use App\Models\ProductSku;
use App\Models\User;
use App\Models\UserAddress;
use Carbon\Carbon;

class OrderService
{
   public function store(User $user,UserAddress $address,$remark,$items)
   {
       //开启一个事务
       $order = \DB::transaction(function () use($user,$address,$remark,$items){
           //更新此地址的最后使用时间
           $address->update(['last_used_at'=>Carbon::now()]);
           //创建一个订单
           $order = new Order([
               'address'    =>[
                   //将地址放在订单中
                   'address' => $address->full_address,
                   'zip'     => $address->zip,
                   'contact_name' => $address->contact_name,
                   'contact_phone' => $address->contact_phone
               ],
               //订单备注
               'remark' => $remark,
               'total_amount' => 0,
           ]);
           //订单关联到当前用户
           $order->user()->associate($user);
           //写入数据库
           $order->save();
           $totalAmount = 0;
           //遍历用户提交的sku
           foreach ($items as $data){
               $sku = ProductSku::find($data['sku_id']);
               //创建一个cartItem 并直接与当前订单关联
               //$order->items()->make() 方法可以新建一个关联关系的对象=$item = new OrderItem(); $item->order()->associate($order)
               $item = $order->items()->make([
                   'amount' => $data['amount'],
                   'price'  => $sku->price,
               ]);
               $item->product()->associate($sku->product_id);
               $item->productSku()->associate($sku);
               $item->save();
               $totalAmount +=$sku->price* $data['amount'];
               if($sku->decreaseStock($data['amount'])<=0){
                   throw new InternalException('库存量不足');
               }
           }
           //更新订单金额
           $order->update(['total_amount'=>$totalAmount]);
           //将下单的商品从购物车中移除
           $skuIds = collect($items)->pluck('sku_id')->all();
           app(CartService::class)->remove($skuIds);
           return $order;
       });
       // 这里我们直接使用 dispatch 函数
       dispatch(new CloseOrder($order,config('app.order_ttl')));
       return $order;
   }
}